/*
 * @Author: rock
 * @Date: 2025-09-30 22:31:11
 * @LastEditors: rock 
 * @LastEditTime: 2025-10-01 17:20:44
 * @FilePath: /Client/main/Client.cpp
 * @Description: Ctrl+Num1-> For Document; Ctrl+Num2-> For Function
 * 
 * Copyright (c) 2025 by rock, All Rights Reserved. 
 */
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>

#include "head.h"
#include "pack.h"

int main()
{
    //1.创建通信套接字
    int cfd = socket(AF_INET, SOCK_STREAM, 0);
    if(cfd == -1)
    {
        perror("socket");
        return -1;
    }

    //2.连接服务器
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(PORT_);
    inet_pton(AF_INET, IP_, &saddr.sin_addr.s_addr);

    int ret = connect(cfd, (struct sockaddr*)&saddr, sizeof(saddr));
    if(ret == -1)
    {
        perror("connect\n");
        return -1;
    }

    //3.向客户端发送数据
    int number = 0;//计数num

    DataPack data;
    data.msg = new char[10]{'1','2','3','4','5','6','7','8','9','\0'}; 
    data.msgLen = 10;  
    char* dataMessage = Pack(data);

    while(1)
    {
        number++;//计数+1
        char buff[1024] = {0};

        memcpy(buff, dataMessage, data.lenPack);
        
        printf("\n循环开始\n");
        printf("发送端数据包的总长度: %d\n", data.lenPack);
        printf("发送端数据的长度: %d\n", data.msgLen);
        printf("发送端的数据头部: %x\n", dataMessage[0]);
        printf("发送端的数据尾部: %x\n", dataMessage[data.lenPack - 1]);
        
        send(cfd, buff, data.lenPack, 0);

        printf("\n等待用户按下回车键...");
        getchar();  
              

        //数组重置
        memset(buff, 0, sizeof(buff));

        int len = recv(cfd, buff, sizeof(buff), 0);
        if(len>0)
        {
            printf("\n收到客户端回到的消息\n");
            printf("Server say: %s\n", data.msg);            
        }
        else if(len == 0)
        {
            printf("服务器已经断开连接\n");
            break;
        }
        else
        {
            perror("recv");
            break;
        }

        printf("\n客户端睡眠一秒钟\n");
        sleep(1);
    }


    //4.关闭套接字
    close(cfd);

    return 0;
    

}